<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <style>
        body {
            font-size: 10px;
        }
        
        #div {
            border: 1px solid gray;
        }
        
        .on {
            color: aquamarine
        }
        
        .leave {
            color: red;
        }
        
        .send {
            color: blue
        }
    </style>
</head>

<body>
    <h5>需要启动服务:node ./nodejs_websocket_server.js 来提供接口</h5>
    <input type="text" id="input"> <button id="button">发送</button>
    <div id="div"></div>

</body>
<script>
    var div = document.querySelector('#div')
    var input = document.querySelector('#input')
    var button = document.querySelector('#button')

    const ON_STATUS = 0;
    const SEND_STATUS = 1;
    const LEAVE_STATUS = 2;

    // 创建websocket服务
    const socket = new WebSocket('ws://localhost:3001');

    // 监听连接
    socket.addEventListener('open', function(event) {
        // div.innerHTML = '新用户上线!'
        console.log('连接到了服务器');
    });

    button.addEventListener('click', function() {
        let value = input.value;
        // 用户发送消息到服务器
        socket.send(value)
        input.value = ''
    })

    // 浏览器监听message事件，只要服务器发送消息到浏览器，就会被执行
    socket.addEventListener('message', function(event) {
        //console.log(event.data);
        let data = JSON.parse(event.data)
        let div1 = document.createElement('div');
        div1.innerHTML = `${data.msg } ------ ${data.time}`
        if (data.type === ON_STATUS) {
            div1.className = 'on'
        } else if (data.type === SEND_STATUS) {
            div1.className = 'send'
        } else {
            div1.className = 'leave'
        }
        div.appendChild(div1)

    });

    socket.addEventListener('close', function() {
        div.innerHTML = '断开服务连接'
    })
</script>

</html>